Nodejs Basic Notes

JavaScript
https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb

https://www.zhihu.com/question/24847805
https://blog.csdn.net/fangjian1204/article/details/50585073

http://www.javacoffeebreak.com/faq/faq0084.html

1. V8

V8 is JavaScript engine (An interpreter which executes JavaScript code)

2. Node.js

Node.js是一个能够在服务器端运行JavaScript的开放源代码、跨平台JavaScript运行环境.
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side

Node.js采用Google开发的V8运行代码,使用事件驱动、非阻塞和异步输入输出模型等技术来提高性能
Node.js uses an event-driven, non-blocking, asynchronous I/O.

###3. networking modules

    net--- for creating TCP based server and clients
    http-- for creating HTTP based web applications
    https -- for creating TLS/SSL clients and severs

###4. undefined & not defined in JavaScript

use a variable that dosen’t exist :var name is not defined
typeof undeclared_variable : return undefined.

    var x; // declaring x
    console.log(x); //output: undefined
    console.log(y);  // Output: ReferenceError: y is not defined

###5. drawback of creating true private method in JavaScript
inefficient to use the memory
because a new copy of the method would be created for each instance

###6. What is “closure” in javascript?
外部函数(external function)获取内部函数私有属性的一种方法

        function myHouse(){
          var __myname = 'Kevin';
          var getMyname = function(){
              return __myname;
          };
          return getMyname;
        }

        var getName = myHouse();
        console.log(getName());//Kevin


    即通过在myHouse()中返回getMyname函数,
    getMyname函数中返回私有变量__myname,
    从而获取私有变量,同时保护私有变量不会直接暴露给外部,
    以免改变私有变量值。

6.1 how would you make a variable read-only

    Method 1. use closure, craete a inner function that returns its value;
    Method 2. use `Object.defineProperty` specific writeable to false & configurable to false

###7. instanceof
instanceof operator checks the current object and return true if the object is of the specified type

###8. Self-Invoking anonymous function or Self-Executing anonymous function.

put ()after their name, the function will run immediately

###9. Object-Based inheritance[继承自一个object]
one object inherit from another object without invoking a constructor function.

Object.create()

###10. Type-Based inheritance[继承自一个function]
need to call constructor function of the object from which you want to inherit.

1.Prototypal Inheritance :

    Employee.prototype = new Person("Nishant", 24,5000);

    var emp1 = new Employee("Google");

    console.log(emp1 instanceof Person); // true
    console.log(emp1 instanceof Employee); // true

2.

    function Super(){
            this.colors=["red","blue"];
        }

    function Sub(){
        Super.call(this);
    }

###11. prevent modification of object in JavaScript

    1.Object.preventExtensions(employee);
    //不能添加新properties or method,但是可以改变原有的

    2.Object.seal(employee);
    //prevent existing properties and methods from being deleted.
    3.Object.freeze(employee); 
    //only readable

###11.1 javascript strict model
“use strict”:

    [ changes previously accepted "bad syntax" 
    into real errors ]
    [ any assignment to a non-writable property will throw an error]
    1. variables must declare
    2. delete is not allowed.
    3.  with() & eval() is not allowed to create variables

###12. when use case for anonymous function

  1. only used in one place

             setTimeout(function(){
                 alert("Hello");
             },1000);
    
  2. Anonymous functions are declared inline and inline functions have advantages in the case that they can access variable in the parent scopes.

     <button id="myBtn"></button>
    
     //Add Event Listener
     var btn = document.getElementById('myBtn');
     btn.addEventListener('click', function () {
       alert('button clicked');
     });
    
     //anonymous function as a callback function in event handler
    
  3. Passing anonymous function as a parameter to calling function.

###13. non-enumerable property
Object can have properties that don’t show up when you iterate through object using for…in loop or using Object.keys()

Data Properties:

  • configurable: for removing via delete,changing the attributes.changing to accessor[比如person的name,可不可以删]
  • enumerable: whether to return in a for-in loop or not
  • writable: for changing the property’s value
  • value: default value is undefined

      const object1 = {};
    
      Object.defineProperty(object1, 'property1', {
        value: 42,
        writable: false
      });
    

###14. callback
A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

###15 event handler
to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter.

 var clickHandler = {
    message: 'click event handler',
    handleClick: function(event) {
        console.log(this.message);
    }
};

var btn = document.getElementById('myBtn');
// Add click event to btn and bind the clickHandler object
btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));

###16. DOM
document object model : access and change the content of the html

###17. handle exceptions
JavaScript supports try, catch, finally and throw keywords for exception handling.

###18. use of history object
to switch to history pages such as back and forward from current page or another page

    history.back()
    history.forward()
    history.go(number)

###19. Factory function.
In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.

###20. var vs. let
The var keyword behaves differently in function scopes and block scopes. A variable declared with var in a function scope can’t be accessed outside that function scope.
so it could avoid hoisting

###Function

  1. getElementById().

     Eg:
     document.getElementById("demo").innerHTML = "Hello JavaScript"
     后面可以跟:
     .src ='pic_bulbon.gif'
     .style.fontSize = "35px"
     .style.display = "none" //hide
     .style.display='block'  //show
    
  1. JavaScript can “display” data in different ways:

     Writing into an HTML element, using innerHTML.
     Writing into the HTML output using document.write().
     Writing into an alert box, using window.alert().
     Writing into the browser console, using console.log().
    
  2. == & ===

     ==    equal to
     ===    equal value and equal type
    
  1. Do Not Declare Strings, Numbers, and Booleans as Objects!
    Object cannot be compared, it will always return false

  2. module.exports

  3. readfile

    require('fs');
    接收到的是一个buffer object,需要decode
    fs.readFile()   //asynchronous
    fs.readFileSync()   //synchronous
    
  4. os Modeule

     require('os')
    
  1. Array

     Recognize an Array
     1. typeof : will return is a object
     2. Array.isArray(fruits); 
     3. fruits instanceof Array 
    
     //从屁股上
     fruits.pop(); 
     fruits.push();
    
     //从脑袋上
     shift() method removes the first array element and "shifts" all other elements to a lower index.
     unshift() method adds a new element to an array (at the beginning),return length of array
    
     splice(,) : remove element
     concat() : merge
     slice()  : create new array
     toString()
    
     //循环遍历数组:
     1. 用splice。delete的话会保留空值
     2. 倒叙遍历,否则有可能出错
    
     while(arrayList.length) {
           arrayList.pop();
     }
    
     //associative array:
     Object.keys(counterArray).length
    
  1. delete operator is used to delete property from object
    所以不能删除全局变量/局部变量
    也不能删除实例的prototype property.

         var Employee = {
           company: 'xyz'
         }
         var emp1 = Object.create(Employee);
         delete emp1.company
         console.log(emp1.company);
    
        [Output]:xyz
        因为emp1不拥有company,company 是个prototype property
        可以通过delete emp1.__proto__.company来删除
  1. call()
    you can use a method belonging to another object.
    Difference Between call() and apply()

         call() takes any function arguments separately.
    
         apply() takes any function arguments as an array.
    
  1. isNaN()
    returns true if the variable value is not a number.

  2. get the reference of a caller function inside a function?

    function func() {

      return arguments.callee; 
    

    }
    func();

  3. eval()

    evaluates or executes an argument.
    
  4. setTimeout(function() {}, 1000);

    calls a function or evaluates an expression after a specified number of milliseconds
    
  5. IIFE

    Immediately Invoked Function Expression (IIFE)

  6. with()
    Specify a default object for one or a group of statements.

总阅读量 :